<template>
  <div class="material">
    <el-card class="list-box" style="border: none; padding: 8px;">
      <div style="width: 100%;">
        <el-tabs v-model="activeName" type="card" @tab-click="handleTabClick">
          <el-tab-pane label="焙烧车间质量表" name="first">
            <div class="select-wrapper">
              <el-form ref="searchForm" :inline="true" :model="searchForm" size="mini">
                <el-form-item label="模板选择:">
                  <el-select v-model="selectedRoastOption" placeholder="请选择" size="mini" @change="handleRoastSelectChange">
                    <el-option v-for="item in ROAST_SELECT_OPTIONS" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
                <el-form-item label="日期查询:">
                  <el-date-picker v-model="searchForm.date" type="date" placeholder="选择日期" size="mini" />
                </el-form-item>
                <el-form-item>
                  <el-button size="mini" type="primary" :loading="searchLoad" @click="handleSearch">查询</el-button>
                  <el-button size="mini" @click="handleReset">重置</el-button>
                </el-form-item>
              </el-form>
            </div>

            <div class="table-title">{{ selectedRoastTitle }}</div>

            <dynamic-quality-table
              v-if="isTableReady"
              :columns="roastColumns"
              :table-data="roastTableData"
              :edit-status="roastEditStatus"
              :table-loading="roastTableLoading"
              :row-height="currentRowHeight"
              :font-size="currentFontSize"
              :row-class-name="roastRowClassName"
              :show-selection="true"
              @toggle-edit="handleToggleEdit"
              @toggle-size="handleSizeChange"
              @refresh="handleTableRefresh"
              @save="handleSave"
              @add-row="handleAddRow"
              @delete-row="handleDeleteRow"
            />
          </el-tab-pane>

          <el-tab-pane label="分报表" name="third">
            <!-- 分报表独立搜索表单 -->
            <div class="select-wrapper">
              <el-form ref="inspectionSearchForm" :inline="true" :model="inspectionSearchForm" size="mini">
                <el-form-item label="模板选择:">
                  <el-select v-model="selectedInspectionTemplate" placeholder="请选择" size="mini" @change="handleInspectionTemplateChange">
                    <el-option v-for="item in INSPECTION_TEMPLATE_OPTIONS" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
                <el-form-item label="日期查询:">
                  <el-date-picker v-model="inspectionSearchForm.date" type="date" placeholder="选择日期" size="mini" />
                </el-form-item>
                <el-form-item>
                  <el-button size="mini" type="primary" :loading="inspectionSearchLoad" @click="handleInspectionSearch">查询</el-button>
                  <el-button size="mini" @click="handleInspectionReset">重置</el-button>
                </el-form-item>
              </el-form>
            </div>

            <div class="table-title">{{ selectedInspectionTitle }}</div>

            <!-- 使用 DynamicQualityTable 组件，但隐藏编辑相关按钮 -->
            <DynamicQualityTable
              v-if="isTableReady"
              :columns="inspectionColumns"
              :table-data="inspectionTableData"
              :edit-status="inspectionEditStatus"
              :table-loading="inspectionTableLoading"
              :span-method="inspectionSpanMethod"
              :row-class-name="inspectionRowClassName"
              :row-height="currentRowHeight"
              :font-size="currentFontSize"
              :show-selection="false"
              :show-edit-button="false"
              :show-add-button="false"
              :show-delete-button="false"
              :show-refresh-button="true"
              :show-size-button="true"
              :show-column-button="true"
              :show-fullscreen-button="true"
              @toggle-edit="handleInspectionToggleEdit"
              @toggle-size="handleSizeChange"
              @save="handleInspectionSave"
              @refresh="handleInspectionRefresh"
            />
          </el-tab-pane>

          <el-tab-pane label="月报表" name="fourth">
            <!-- 月报表独立搜索表单 -->
            <div class="select-wrapper">
              <el-form ref="monthlySearchForm" :inline="true" :model="monthlySearchForm" size="mini">
                <el-form-item label="模板选择:">
                  <el-select v-model="selectedMonthlyTemplate" placeholder="请选择" size="mini" @change="handleMonthlyTemplateChange">
                    <el-option v-for="item in MONTHLY_TEMPLATE_OPTIONS" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
                <el-form-item label="日期查询:">
                  <el-date-picker v-model="monthlySearchForm.date" type="date" placeholder="选择日期" size="mini" />
                </el-form-item>
                <el-form-item>
                  <el-button size="mini" type="primary" :loading="monthlySearchLoad" @click="handleMonthlySearch">查询</el-button>
                  <el-button size="mini" @click="handleMonthlyReset">重置</el-button>
                </el-form-item>
              </el-form>
            </div>

            <div class="table-title">{{ selectedMonthlyTitle }}</div>

            <!-- 使用 DynamicQualityTable 组件 -->
            <DynamicQualityTable
              v-if="isTableReady"
              :columns="monthlyColumns"
              :table-data="monthlyTableData"
              :edit-status="monthlyEditStatus"
              :table-loading="monthlyTableLoading"
              :row-class-name="monthlyRowClassName"
              :row-height="currentRowHeight"
              :font-size="currentFontSize"
              :show-selection="false"
              :show-edit-button="false"
              :show-add-button="false"
              :show-delete-button="false"
              :show-refresh-button="true"
              :show-size-button="true"
              :show-column-button="true"
              :show-fullscreen-button="true"
              @toggle-size="handleSizeChange"
              @refresh="handleMonthlyRefresh"
            />
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-card>
  </div>
</template>

<script>
import DynamicQualityTable from '../components/DynamicQualityTable.vue'

// 焙烧车间质量表列配置
const _ROAST_COLUMNS = Object.freeze([
  { label: '日期', prop: 'date', type: 'date-picker', minWidth: 110, fixed: true },
  { label: '出炉', prop: 'outputNum', type: 'number-input', minWidth: 65, min: 0 },
  { label: '代清', prop: 'agentCleanNum', type: 'number-input', minWidth: 65, min: 0 },
  { label: '未清', prop: 'uncleanNum', type: 'number-input', minWidth: 65, min: 0 },
  { label: '合格', prop: 'qualifiedNum', type: 'number-input', minWidth: 65, min: 0 },
  { label: '废品', prop: 'wasteNum', type: 'number-input', minWidth: 65, min: 0 },
  { label: '待发', prop: 'pendingSendNum', type: 'number-input', minWidth: 65, min: 0 },
  {
    label: '废块原因',
    children: Object.freeze([
      { label: '起包', prop: 'waste_bag', type: 'number-input', minWidth: 50, min: 0 },
      { label: '车间', prop: 'waste_workshop', type: 'number-input', minWidth: 50, min: 0 },
      { label: '粘连', prop: 'waste_adhere', type: 'number-input', minWidth: 50, min: 0 },
      { label: '清工摔', prop: 'waste_drop', type: 'number-input', minWidth: 50, min: 0 },
      { label: '氧化', prop: 'waste_oxidation', type: 'number-input', minWidth: 50, min: 0 },
      { label: '横裂', prop: 'waste_horizontalCrack', type: 'number-input', minWidth: 50, min: 0 },
      { label: '纵裂', prop: 'waste_verticalCrack', type: 'number-input', minWidth: 50, min: 0 },
      { label: '小头空', prop: 'waste_smallHeadEmpty', type: 'number-input', minWidth: 50, min: 0 },
      { label: '角裂纹', prop: 'waste_cornerCrack', type: 'number-input', minWidth: 50, min: 0 },
      { label: '碗裂纹', prop: 'waste_bowlCrack', type: 'number-input', minWidth: 50, min: 0 },
      { label: '叉车', prop: 'waste_forklift', type: 'number-input', minWidth: 50, min: 0 }
    ])
  },
  {
    label: '待发原因',
    children: Object.freeze([
      { label: '起包', prop: 'pending_bag', type: 'number-input', minWidth: 50, min: 0 },
      { label: '碰角', prop: 'pending_corner', type: 'number-input', minWidth: 50, min: 0 },
      { label: '出炉掉角', prop: 'pending_dropCorner', type: 'number-input', minWidth: 50, min: 0 },
      { label: '粘连', prop: 'pending_adhere', type: 'number-input', minWidth: 50, min: 0 },
      { label: '氧化', prop: 'pending_oxidation', type: 'number-input', minWidth: 50, min: 0 },
      { label: '横裂', prop: 'pending_horizontalCrack', type: 'number-input', minWidth: 50, min: 0 },
      { label: '纵裂', prop: 'pending_verticalCrack', type: 'number-input', minWidth: 50, min: 0 },
      { label: '小头空', prop: 'pending_smallHeadEmpty', type: 'number-input', minWidth: 50, min: 0 },
      { label: '角裂纹', prop: 'pending_cornerCrack', type: 'number-input', minWidth: 50, min: 0 },
      { label: '碗底裂', prop: 'pending_bowlBottomCrack', type: 'number-input', minWidth: 50, min: 0 },
      { label: '叉车', prop: 'pending_forklift', type: 'number-input', minWidth: 50, min: 0 }
    ])
  }
])

const _ROAST_SELECT_OPTIONS = Object.freeze([
  { label: '东系统固阳块', value: 'roast1' },
  { label: '西系统固阳块', value: 'roast2' },
  { label: '东系统扎铝块', value: 'roast3' },
  { label: '西系统扎铝块', value: 'roast4' }
])

// 检验统计表模版选项
const _INSPECTION_TEMPLATE_OPTIONS = Object.freeze([
  { label: '河北鸿科碳素焙烧一车间2025年9月份检验统计', value: 'inspection1', workshop: '焙烧一车间', year: 2025, month: 9 },
  { label: '河北鸿科碳素焙烧一车间2025年10月份检验统计', value: 'inspection2', workshop: '焙烧一车间', year: 2025, month: 10 },
  { label: '河北鸿科碳素焙烧二车间2025年9月份检验统计', value: 'inspection3', workshop: '焙烧二车间', year: 2025, month: 9 },
  { label: '河北鸿科碳素焙烧二车间2025年10月份检验统计', value: 'inspection4', workshop: '焙烧二车间', year: 2025, month: 10 }
])

// 月报表模版选项
const _MONTHLY_TEMPLATE_OPTIONS = Object.freeze([
  { label: '河北鸿科碳素焙烧一车间2025年9月份检验统计', value: 'monthly1', workshop: '焙烧一车间', year: 2025, month: 9 },
  { label: '河北鸿科碳素焙烧一车间2025年10月份检验统计', value: 'monthly2', workshop: '焙烧一车间', year: 2025, month: 10 },
  { label: '河北鸿科碳素焙烧二车间2025年9月份检验统计', value: 'monthly3', workshop: '焙烧二车间', year: 2025, month: 9 },
  { label: '河北鸿科碳素焙烧二车间2025年10月份检验统计', value: 'monthly4', workshop: '焙烧二车间', year: 2025, month: 10 }
])

// 月报表列配置
const _MONTHLY_COLUMNS = Object.freeze([
  { label: '产品名称', prop: 'productName', type: 'text', minWidth: 120, fixed: true },
  { label: '检验块数', prop: 'inspectedCount', type: 'number-input', minWidth: 80, min: 0 },
  { label: '合格块数', prop: 'qualifiedCount', type: 'number-input', minWidth: 80, min: 0 },
  { label: '废品块数', prop: 'wasteCount', type: 'number-input', minWidth: 80, min: 0 },
  { label: '待发块数', prop: 'pendingCount', type: 'number-input', minWidth: 80, min: 0 },
  {
    label: '废品原因',
    children: Object.freeze([
      { label: '横裂', prop: 'waste_horizontalCrack', type: 'number-input', minWidth: 60, min: 0 },
      { label: '纵裂', prop: 'waste_verticalCrack', type: 'number-input', minWidth: 60, min: 0 },
      { label: '氧化', prop: 'waste_oxidation', type: 'number-input', minWidth: 60, min: 0 },
      { label: '联温裂', prop: 'waste_tempCrack', type: 'number-input', minWidth: 70, min: 0 },
      { label: '碰伤', prop: 'waste_damage', type: 'number-input', minWidth: 60, min: 0 }
    ])
  },
  {
    label: '待发原因',
    children: Object.freeze([
      { label: '横裂', prop: 'pending_horizontalCrack', type: 'number-input', minWidth: 60, min: 0 },
      { label: '纵裂', prop: 'pending_verticalCrack', type: 'number-input', minWidth: 60, min: 0 },
      { label: '联温裂', prop: 'pending_tempCrack', type: 'number-input', minWidth: 70, min: 0 },
      { label: '碰伤', prop: 'pending_damage', type: 'number-input', minWidth: 60, min: 0 },
      { label: '起包', prop: 'pending_bag', type: 'number-input', minWidth: 60, min: 0 },
      { label: '氧化', prop: 'pending_oxidation', type: 'number-input', minWidth: 60, min: 0 }
    ])
  }
])

// 检验统计表列配置
const _INSPECTION_COLUMNS = Object.freeze([
  { label: '系统', prop: 'system', type: 'text', minWidth: 60, fixed: true, needMerge: true },
  { label: '产品名称', prop: 'productName', type: 'text', minWidth: 100, fixed: true, needMerge: true },
  { label: '检验块数', prop: 'inspectedCount', type: 'number-input', minWidth: 80, min: 0 },
  { label: '合格块数', prop: 'qualifiedCount', type: 'number-input', minWidth: 80, min: 0 },
  { label: '废品块数', prop: 'wasteCount', type: 'number-input', minWidth: 80, min: 0 },
  { label: '待发块数', prop: 'pendingCount', type: 'number-input', minWidth: 80, min: 0 },
  {
    label: '废品原因',
    children: Object.freeze([
      { label: '掉块', prop: 'waste_drop', type: 'number-input', minWidth: 60, min: 0 },
      { label: '纵裂', prop: 'waste_verticalCrack', type: 'number-input', minWidth: 60, min: 0 },
      { label: '氧化', prop: 'waste_oxidation', type: 'number-input', minWidth: 60, min: 0 },
      { label: '联温裂', prop: 'waste_tempCrack', type: 'number-input', minWidth: 70, min: 0 },
      { label: '碰伤', prop: 'waste_damage', type: 'number-input', minWidth: 60, min: 0 }
    ])
  },
  {
    label: '待发原因',
    children: Object.freeze([
      { label: '掉块', prop: 'pending_drop', type: 'number-input', minWidth: 60, min: 0 },
      { label: '纵裂', prop: 'pending_verticalCrack', type: 'number-input', minWidth: 60, min: 0 },
      { label: '联温裂', prop: 'pending_tempCrack', type: 'number-input', minWidth: 70, min: 0 },
      { label: '碰伤', prop: 'pending_damage', type: 'number-input', minWidth: 60, min: 0 },
      { label: '起包', prop: 'pending_bag', type: 'number-input', minWidth: 60, min: 0 },
      { label: '氧化', prop: 'pending_oxidation', type: 'number-input', minWidth: 60, min: 0 }
    ])
  }
])

const SIZE_PRESETS = Object.freeze([
  { size: 'mini', rowHeight: 30, fontSize: 12, label: '紧凑' },
  { size: 'small', rowHeight: 36, fontSize: 13, label: '默认' },
  { size: 'medium', rowHeight: 42, fontSize: 14, label: '宽松' }
])

export default {
  name: 'FormManegerList',
  components: { DynamicQualityTable },
  data() {
    return {
      activeName: 'first',
      searchLoad: false,
      // 焙烧车间搜索表单（独立）
      searchForm: { date: '' },
      roastTableDataRaw: [],
      roastTableDataBackup: [],
      roastEditStatus: false,
      roastTableLoading: false,
      isTableReady: false,
      sizeIndex: 0,
      ROAST_SELECT_OPTIONS: _ROAST_SELECT_OPTIONS,
      selectedRoastOption: _ROAST_SELECT_OPTIONS[0].value,
      // 检验统计表数据
      inspectionTableDataRaw: [],
      inspectionTableDataBackup: [],
      inspectionEditStatus: false,
      inspectionTableLoading: false,
      // 分报表搜索表单（独立）
      inspectionSearchForm: { date: '' },
      inspectionSearchLoad: false,
      INSPECTION_TEMPLATE_OPTIONS: _INSPECTION_TEMPLATE_OPTIONS,
      selectedInspectionTemplate: _INSPECTION_TEMPLATE_OPTIONS[0].value,
      // 月报表数据
      monthlyTableDataRaw: [],
      monthlyTableDataBackup: [],
      monthlyEditStatus: false,
      monthlyTableLoading: false,
      // 月报表搜索表单（独立）
      monthlySearchForm: { date: '' },
      monthlySearchLoad: false,
      MONTHLY_TEMPLATE_OPTIONS: _MONTHLY_TEMPLATE_OPTIONS,
      selectedMonthlyTemplate: _MONTHLY_TEMPLATE_OPTIONS[0].value
    }
  },
  computed: {
    selectedRoastTitle() {
      return this.ROAST_SELECT_OPTIONS.find(item => item.value === this.selectedRoastOption).label
    },
    selectedInspectionTitle() {
      return this.INSPECTION_TEMPLATE_OPTIONS.find(item => item.value === this.selectedInspectionTemplate).label
    },
    selectedMonthlyTitle() {
      return this.MONTHLY_TEMPLATE_OPTIONS.find(item => item.value === this.selectedMonthlyTemplate).label
    },
    currentRowHeight() {
      return SIZE_PRESETS[this.sizeIndex].rowHeight
    },
    currentFontSize() {
      return SIZE_PRESETS[this.sizeIndex].fontSize
    },
    roastColumns() {
      return _ROAST_COLUMNS
    },
    inspectionColumns() {
      return _INSPECTION_COLUMNS
    },
    monthlyColumns() {
      return _MONTHLY_COLUMNS
    },
    roastTableData() {
      if (!this.roastTableDataRaw || this.roastTableDataRaw.length === 0) {
        return []
      }
      const data = [...this.roastTableDataRaw]
      const totalRow = this.calculateRoastTotals(this.roastTableDataRaw)
      data.push(totalRow)
      return data
    },
    inspectionTableData() {
      if (!this.inspectionTableDataRaw || this.inspectionTableDataRaw.length === 0) {
        return []
      }
      const data = [...this.inspectionTableDataRaw]
      const totalRow = this.calculateInspectionTotals(this.inspectionTableDataRaw)
      data.push(totalRow)
      return data
    },
    monthlyTableData() {
      if (!this.monthlyTableDataRaw || this.monthlyTableDataRaw.length === 0) {
        return []
      }
      const data = [...this.monthlyTableDataRaw]
      const totalRow = this.calculateMonthlyTotals(this.monthlyTableDataRaw)
      data.push(totalRow)
      return data
    }
  },
  mounted() {
    setTimeout(() => {
      this.roastTableDataRaw = this.getRoastMockTableData(this.selectedRoastOption)
      this.inspectionTableDataRaw = this.getInspectionMockData()
      this.monthlyTableDataRaw = this.getMonthlyMockData()
      this.isTableReady = true
    }, 300)
  },
  beforeDestroy() {
    this.roastTableDataRaw = []
    this.searchForm = null
  },
  methods: {
    handleTabClick(tab) {
      if (tab.name === 'first' && !this.roastTableDataRaw.length) {
        this.roastTableDataRaw = this.getRoastMockTableData(this.selectedRoastOption)
      } else if (tab.name === 'third' && !this.inspectionTableDataRaw.length) {
        this.inspectionTableDataRaw = this.getInspectionMockData()
      }
    },
    handleRoastSelectChange(value) {
      this.selectedRoastOption = value
      this.roastTableDataRaw = this.getRoastMockTableData(value)
    },
    getRoastMockTableData(blockType, rowCount = 31) {
      const data = []
      const year = 2025
      const month = 10

      for (let day = 1; day <= rowCount && day <= 31; day++) {
        const formatDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`
        const baseOutput = 28 + Math.floor(Math.random() * 10)
        const baseAgent = 6 + Math.floor(Math.random() * 6)
        const baseUnclean = 3 + Math.floor(Math.random() * 5)
        const baseQualified = baseOutput - Math.floor(Math.random() * 5)
        const baseWaste = 2 + Math.floor(Math.random() * 4)
        const basePending = 15 + Math.floor(Math.random() * 10)

        data.push({
          id: `${blockType}_${day}`,
          date: formatDate,
          outputNum: baseOutput,
          agentCleanNum: baseAgent,
          uncleanNum: baseUnclean,
          qualifiedNum: baseQualified,
          wasteNum: baseWaste,
          pendingSendNum: basePending,
          waste_bag: Math.floor(Math.random() * 3) + 1,
          waste_workshop: Math.floor(Math.random() * 3),
          waste_adhere: Math.floor(Math.random() * 3) + 1,
          waste_drop: Math.floor(Math.random() * 3),
          waste_oxidation: Math.floor(Math.random() * 3) + 1,
          waste_horizontalCrack: Math.floor(Math.random() * 3),
          waste_verticalCrack: Math.floor(Math.random() * 3) + 1,
          waste_smallHeadEmpty: Math.floor(Math.random() * 3),
          waste_cornerCrack: Math.floor(Math.random() * 3) + 1,
          waste_bowlCrack: Math.floor(Math.random() * 3),
          waste_forklift: Math.floor(Math.random() * 3) + 1,
          pending_bag: Math.floor(Math.random() * 3),
          pending_corner: Math.floor(Math.random() * 3) + 1,
          pending_dropCorner: Math.floor(Math.random() * 3),
          pending_adhere: Math.floor(Math.random() * 3) + 1,
          pending_oxidation: Math.floor(Math.random() * 3),
          pending_horizontalCrack: Math.floor(Math.random() * 3) + 1,
          pending_verticalCrack: Math.floor(Math.random() * 3),
          pending_smallHeadEmpty: Math.floor(Math.random() * 3) + 1,
          pending_cornerCrack: Math.floor(Math.random() * 3),
          pending_bowlBottomCrack: Math.floor(Math.random() * 3) + 1,
          pending_forklift: Math.floor(Math.random() * 3)
        })
      }

      return data
    },
    calculateRoastTotals(data) {
      const total = {
        id: 'total_row',
        date: '合计',
        outputNum: 0,
        agentCleanNum: 0,
        uncleanNum: 0,
        qualifiedNum: 0,
        wasteNum: 0,
        pendingSendNum: 0,
        waste_bag: 0,
        waste_workshop: 0,
        waste_adhere: 0,
        waste_drop: 0,
        waste_oxidation: 0,
        waste_horizontalCrack: 0,
        waste_verticalCrack: 0,
        waste_smallHeadEmpty: 0,
        waste_cornerCrack: 0,
        waste_bowlCrack: 0,
        waste_forklift: 0,
        pending_bag: 0,
        pending_corner: 0,
        pending_dropCorner: 0,
        pending_adhere: 0,
        pending_oxidation: 0,
        pending_horizontalCrack: 0,
        pending_verticalCrack: 0,
        pending_smallHeadEmpty: 0,
        pending_cornerCrack: 0,
        pending_bowlBottomCrack: 0,
        pending_forklift: 0,
        isTotal: true
      }

      data.forEach(row => {
        total.outputNum += row.outputNum
        total.agentCleanNum += row.agentCleanNum
        total.uncleanNum += row.uncleanNum
        total.qualifiedNum += row.qualifiedNum
        total.wasteNum += row.wasteNum
        total.pendingSendNum += row.pendingSendNum
        total.waste_bag += row.waste_bag
        total.waste_workshop += row.waste_workshop
        total.waste_adhere += row.waste_adhere
        total.waste_drop += row.waste_drop
        total.waste_oxidation += row.waste_oxidation
        total.waste_horizontalCrack += row.waste_horizontalCrack
        total.waste_verticalCrack += row.waste_verticalCrack
        total.waste_smallHeadEmpty += row.waste_smallHeadEmpty
        total.waste_cornerCrack += row.waste_cornerCrack
        total.waste_bowlCrack += row.waste_bowlCrack
        total.waste_forklift += row.waste_forklift
        total.pending_bag += row.pending_bag
        total.pending_corner += row.pending_corner
        total.pending_dropCorner += row.pending_dropCorner
        total.pending_adhere += row.pending_adhere
        total.pending_oxidation += row.pending_oxidation
        total.pending_horizontalCrack += row.pending_horizontalCrack
        total.pending_verticalCrack += row.pending_verticalCrack
        total.pending_smallHeadEmpty += row.pending_smallHeadEmpty
        total.pending_cornerCrack += row.pending_cornerCrack
        total.pending_bowlBottomCrack += row.pending_bowlBottomCrack
        total.pending_forklift += row.pending_forklift
      })

      return total
    },
    roastRowClassName({ row, rowIndex }) {
      if (row.isTotal) {
        return 'total-row'
      }
      return ''
    },
    handleAddRow({ row, position }) {
      const newRow = this.createNewRow(row, position)
      const index = this.roastTableDataRaw.findIndex(item => item.id === row.id)

      if (index === -1) {
        this.$message.error('未找到选中的行')
        return
      }

      if (position === 'before') {
        this.roastTableDataRaw.splice(index, 0, newRow)
      } else {
        this.roastTableDataRaw.splice(index + 1, 0, newRow)
      }

      this.$message.success('添加成功')
    },
    handleDeleteRow({ rows }) {
      const idsToDelete = rows.map(row => row.id)
      this.roastTableDataRaw = this.roastTableDataRaw.filter(
        row => !idsToDelete.includes(row.id)
      )

      const count = rows.length
      this.$message.success(`成功删除 ${count} 行数据`)
    },
    createNewRow(baseRow, position) {
      const currentDate = new Date(baseRow.date)
      let newDate
      if (position === 'before') {
        newDate = new Date(currentDate)
        newDate.setDate(currentDate.getDate() - 1)
      } else {
        newDate = new Date(currentDate)
        newDate.setDate(currentDate.getDate() + 1)
      }

      const year = newDate.getFullYear()
      const month = (newDate.getMonth() + 1).toString().padStart(2, '0')
      const day = newDate.getDate().toString().padStart(2, '0')
      const formatDate = `${year}-${month}-${day}`

      const timestamp = Date.now()
      const newId = `${this.selectedRoastOption}_${timestamp}`

      return {
        id: newId,
        date: formatDate,
        outputNum: 0,
        agentCleanNum: 0,
        uncleanNum: 0,
        qualifiedNum: 0,
        wasteNum: 0,
        pendingSendNum: 0,
        waste_bag: 0,
        waste_workshop: 0,
        waste_adhere: 0,
        waste_drop: 0,
        waste_oxidation: 0,
        waste_horizontalCrack: 0,
        waste_verticalCrack: 0,
        waste_smallHeadEmpty: 0,
        waste_cornerCrack: 0,
        waste_bowlCrack: 0,
        waste_forklift: 0,
        pending_bag: 0,
        pending_corner: 0,
        pending_dropCorner: 0,
        pending_adhere: 0,
        pending_oxidation: 0,
        pending_horizontalCrack: 0,
        pending_verticalCrack: 0,
        pending_smallHeadEmpty: 0,
        pending_cornerCrack: 0,
        pending_bowlBottomCrack: 0,
        pending_forklift: 0
      }
    },
    handleReset() {
      this.$refs.searchForm.resetFields()
      this.roastTableDataRaw = this.getRoastMockTableData(this.selectedRoastOption)
    },
    handleSearch() {
      this.searchLoad = true
      const searchDate = this.searchForm.date ? this.formatDate(this.searchForm.date) : ''
      setTimeout(() => {
        this.roastTableDataRaw = searchDate
          ? this.getRoastMockTableData(this.selectedRoastOption).filter(item => item.date === searchDate)
          : this.getRoastMockTableData(this.selectedRoastOption)
        this.searchLoad = false
      }, 300)
    },
    formatDate(date) {
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    handleTableRefresh() {
      this.roastTableLoading = true
      setTimeout(() => {
        this.roastTableDataRaw = this.getRoastMockTableData(this.selectedRoastOption, 31)
        this.roastTableLoading = false
      }, 500)
    },
    handleSizeChange(sizeName) {
      const preset = SIZE_PRESETS.find(p => p.size === sizeName)
      if (preset) {
        this.sizeIndex = SIZE_PRESETS.indexOf(preset)
      }
    },
    handleToggleEdit() {
      if (!this.roastEditStatus) {
        this.roastTableDataBackup = JSON.parse(JSON.stringify(this.roastTableDataRaw))
        this.roastEditStatus = true
      } else {
        this.$confirm('是否取消编辑并放弃修改?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '继续编辑',
          type: 'warning'
        }).then(() => {
          this.roastTableDataRaw = JSON.parse(JSON.stringify(this.roastTableDataBackup))
          this.roastEditStatus = false
          this.roastTableDataBackup = []
        }).catch(() => {})
      }
    },
    handleSave() {
      this.$confirm('确认保存当前修改?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        setTimeout(() => {
          this.$message.success('保存成功')
          this.roastEditStatus = false
          this.roastTableDataBackup = []
          console.log('保存的数据:', this.roastTableDataRaw)
        }, 500)
      }).catch(() => {})
    },

    // ========== 检验统计表相关方法 ==========

    /**
     * 单元格合并方法
     * 实现规则：
     * 1. 产品名称列：东、西两行合并（跨2行）
     * 2. 小计行：系统列和产品名称列合并（跨2列），显示"小计"
     * 3. 总计行：系统列和产品名称列合并（跨2列），显示"总计"
     */
    inspectionSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 总计行处理
      if (row.isTotal) {
        if (columnIndex === 0) {
          return { rowspan: 1, colspan: 2 }
        } else if (columnIndex === 1) {
          return { rowspan: 0, colspan: 0 }
        }
        return
      }

      const rowInGroup = rowIndex % 3 // 0=东, 1=西, 2=小计

      // 小计行（每组的第3行）
      if (rowInGroup === 2) {
        if (columnIndex === 0) {
          return { rowspan: 1, colspan: 2 }
        } else if (columnIndex === 1) {
          return { rowspan: 0, colspan: 0 }
        }
      }

      // 产品名称列（非小计行）
      if (columnIndex === 1 && rowInGroup !== 2) {
        if (rowInGroup === 0) {
          // 东系统行：跨2行（东+西）
          return { rowspan: 2, colspan: 1 }
        } else if (rowInGroup === 1) {
          // 西系统行：被东系统行合并，隐藏
          return { rowspan: 0, colspan: 0 }
        }
      }
    },

    /**
     * 生成检验统计表模拟数据
     * 数据结构：每个产品3行（东、西、小计）
     */
    getInspectionMockData() {
      const products = [
        { name: '白音华块', eastInspected: 419, eastQualified: 412, westInspected: 415, westQualified: 406 },
        { name: '南山块', eastInspected: 1781, eastQualified: 1761, westInspected: 1738, westQualified: 1714 },
        { name: '朔州块', eastInspected: 2, eastQualified: 2, westInspected: 8, westQualified: 8 },
        { name: '孔铝块', eastInspected: 187, eastQualified: 186, westInspected: 309, westQualified: 301 },
        { name: '圆阳块', eastInspected: 60, eastQualified: 59, westInspected: 18, westQualified: 18 }
      ]

      const data = []
      products.forEach(product => {
        // 东系统数据
        const eastWaste = product.eastInspected - product.eastQualified
        const eastPending = Math.floor(Math.random() * 10) + 1
        data.push({
          id: `${product.name}_east`,
          system: '东',
          productName: product.name,
          inspectedCount: product.eastInspected,
          qualifiedCount: product.eastQualified,
          wasteCount: eastWaste,
          pendingCount: eastPending,
          waste_drop: Math.floor(eastWaste * 0.4),
          waste_verticalCrack: Math.floor(eastWaste * 0.2),
          waste_oxidation: Math.floor(eastWaste * 0.1),
          waste_tempCrack: Math.floor(eastWaste * 0.2),
          waste_damage: eastWaste - Math.floor(eastWaste * 0.9),
          pending_drop: Math.floor(eastPending * 0.3),
          pending_verticalCrack: Math.floor(eastPending * 0.2),
          pending_tempCrack: Math.floor(eastPending * 0.1),
          pending_damage: Math.floor(eastPending * 0.2),
          pending_bag: Math.floor(eastPending * 0.1),
          pending_oxidation: eastPending - Math.floor(eastPending * 0.9)
        })

        // 西系统数据
        const westWaste = product.westInspected - product.westQualified
        const westPending = Math.floor(Math.random() * 10) + 1
        data.push({
          id: `${product.name}_west`,
          system: '西',
          productName: product.name,
          inspectedCount: product.westInspected,
          qualifiedCount: product.westQualified,
          wasteCount: westWaste,
          pendingCount: westPending,
          waste_drop: Math.floor(westWaste * 0.3),
          waste_verticalCrack: Math.floor(westWaste * 0.3),
          waste_oxidation: Math.floor(westWaste * 0.1),
          waste_tempCrack: Math.floor(westWaste * 0.2),
          waste_damage: westWaste - Math.floor(westWaste * 0.9),
          pending_drop: Math.floor(westPending * 0.3),
          pending_verticalCrack: Math.floor(westPending * 0.2),
          pending_tempCrack: Math.floor(westPending * 0.1),
          pending_damage: Math.floor(westPending * 0.2),
          pending_bag: Math.floor(westPending * 0.1),
          pending_oxidation: westPending - Math.floor(westPending * 0.9)
        })

        // 小计行（关键：productName 设置为空字符串，避免在合并失效时显示品种名）
        const totalInspected = product.eastInspected + product.westInspected
        const totalQualified = product.eastQualified + product.westQualified
        const totalWaste = eastWaste + westWaste
        const totalPending = eastPending + westPending
        data.push({
          id: `${product.name}_subtotal`,
          system: '小计',
          productName: '', // 小计行不显示产品名称，因为系统列会合并两列
          inspectedCount: totalInspected,
          qualifiedCount: totalQualified,
          wasteCount: totalWaste,
          pendingCount: totalPending,
          waste_drop: data[data.length - 2].waste_drop + data[data.length - 1].waste_drop,
          waste_verticalCrack: data[data.length - 2].waste_verticalCrack + data[data.length - 1].waste_verticalCrack,
          waste_oxidation: data[data.length - 2].waste_oxidation + data[data.length - 1].waste_oxidation,
          waste_tempCrack: data[data.length - 2].waste_tempCrack + data[data.length - 1].waste_tempCrack,
          waste_damage: data[data.length - 2].waste_damage + data[data.length - 1].waste_damage,
          pending_drop: data[data.length - 2].pending_drop + data[data.length - 1].pending_drop,
          pending_verticalCrack: data[data.length - 2].pending_verticalCrack + data[data.length - 1].pending_verticalCrack,
          pending_tempCrack: data[data.length - 2].pending_tempCrack + data[data.length - 1].pending_tempCrack,
          pending_damage: data[data.length - 2].pending_damage + data[data.length - 1].pending_damage,
          pending_bag: data[data.length - 2].pending_bag + data[data.length - 1].pending_bag,
          pending_oxidation: data[data.length - 2].pending_oxidation + data[data.length - 1].pending_oxidation
        })
      })

      return data
    },

    /**
     * 计算检验统计表总计行
     */
    calculateInspectionTotals(data) {
      const total = {
        id: 'inspection_total_row',
        system: '总计',
        productName: '',
        inspectedCount: 0,
        qualifiedCount: 0,
        wasteCount: 0,
        pendingCount: 0,
        waste_drop: 0,
        waste_verticalCrack: 0,
        waste_oxidation: 0,
        waste_tempCrack: 0,
        waste_damage: 0,
        pending_drop: 0,
        pending_verticalCrack: 0,
        pending_tempCrack: 0,
        pending_damage: 0,
        pending_bag: 0,
        pending_oxidation: 0,
        isTotal: true
      }

      data.forEach(row => {
        // 跳过小计行，避免重复累加（小计行已经是东+西的和，不应该再次累加）
        if (row.system === '小计') {
          return
        }

        total.inspectedCount += row.inspectedCount || 0
        total.qualifiedCount += row.qualifiedCount || 0
        total.wasteCount += row.wasteCount || 0
        total.pendingCount += row.pendingCount || 0
        total.waste_drop += row.waste_drop || 0
        total.waste_verticalCrack += row.waste_verticalCrack || 0
        total.waste_oxidation += row.waste_oxidation || 0
        total.waste_tempCrack += row.waste_tempCrack || 0
        total.waste_damage += row.waste_damage || 0
        total.pending_drop += row.pending_drop || 0
        total.pending_verticalCrack += row.pending_verticalCrack || 0
        total.pending_tempCrack += row.pending_tempCrack || 0
        total.pending_damage += row.pending_damage || 0
        total.pending_bag += row.pending_bag || 0
        total.pending_oxidation += row.pending_oxidation || 0
      })

      return total
    },

    /**
     * 检验统计表行样式类名
     */
    inspectionRowClassName({ row, rowIndex }) {
      if (row.isTotal || row.system === '小计') {
        return 'total-row'
      }
      return ''
    },

    /**
     * 生成月报表模拟数据
     * 数据结构：每个产品1行，共11个产品
     */
    getMonthlyMockData() {
      const products = [
        { name: '白音华块', inspected: 834, qualified: 818 },
        { name: '南山块', inspected: 3519, qualified: 3475 },
        { name: '朔州块', inspected: 10, qualified: 10 },
        { name: '扎铝块', inspected: 496, qualified: 487 },
        { name: '固阳块', inspected: 78, qualified: 77 },
        { name: '锦联大块', inspected: 30, qualified: 30 },
        { name: '银旺泰兴大块', inspected: 101, qualified: 100 },
        { name: '并新百河块', inspected: 350, qualified: 337 },
        { name: '鸿祥百河块', inspected: 159, qualified: 155 },
        { name: '鸿祥白音华块', inspected: 655, qualified: 624 },
        { name: '鸿祥宏泰块', inspected: 1511, qualified: 1412 }
      ]

      const data = []
      products.forEach((product, index) => {
        const wasteTotal = product.inspected - product.qualified
        const pendingTotal = Math.floor(wasteTotal * 0.6)

        data.push({
          id: `monthly_${index + 1}`,
          productName: product.name,
          inspectedCount: product.inspected,
          qualifiedCount: product.qualified,
          wasteCount: wasteTotal,
          pendingCount: pendingTotal,
          waste_horizontalCrack: Math.floor(wasteTotal * 0.2),
          waste_verticalCrack: Math.floor(wasteTotal * 0.3),
          waste_oxidation: Math.floor(wasteTotal * 0.05),
          waste_tempCrack: Math.floor(wasteTotal * 0.25),
          waste_damage: wasteTotal - Math.floor(wasteTotal * 0.8),
          pending_horizontalCrack: Math.floor(pendingTotal * 0.25),
          pending_verticalCrack: Math.floor(pendingTotal * 0.2),
          pending_tempCrack: Math.floor(pendingTotal * 0.1),
          pending_damage: Math.floor(pendingTotal * 0.15),
          pending_bag: Math.floor(pendingTotal * 0.1),
          pending_oxidation: pendingTotal - Math.floor(pendingTotal * 0.8)
        })
      })

      return data
    },

    /**
     * 计算月报表合计行
     */
    calculateMonthlyTotals(data) {
      const total = {
        id: 'monthly_total_row',
        productName: '合计',
        inspectedCount: 0,
        qualifiedCount: 0,
        wasteCount: 0,
        pendingCount: 0,
        waste_horizontalCrack: 0,
        waste_verticalCrack: 0,
        waste_oxidation: 0,
        waste_tempCrack: 0,
        waste_damage: 0,
        pending_horizontalCrack: 0,
        pending_verticalCrack: 0,
        pending_tempCrack: 0,
        pending_damage: 0,
        pending_bag: 0,
        pending_oxidation: 0,
        isTotal: true
      }

      data.forEach(row => {
        total.inspectedCount += row.inspectedCount || 0
        total.qualifiedCount += row.qualifiedCount || 0
        total.wasteCount += row.wasteCount || 0
        total.pendingCount += row.pendingCount || 0
        total.waste_horizontalCrack += row.waste_horizontalCrack || 0
        total.waste_verticalCrack += row.waste_verticalCrack || 0
        total.waste_oxidation += row.waste_oxidation || 0
        total.waste_tempCrack += row.waste_tempCrack || 0
        total.waste_damage += row.waste_damage || 0
        total.pending_horizontalCrack += row.pending_horizontalCrack || 0
        total.pending_verticalCrack += row.pending_verticalCrack || 0
        total.pending_tempCrack += row.pending_tempCrack || 0
        total.pending_damage += row.pending_damage || 0
        total.pending_bag += row.pending_bag || 0
        total.pending_oxidation += row.pending_oxidation || 0
      })

      return total
    },

    /**
     * 月报表行样式类名
     */
    monthlyRowClassName({ row, rowIndex }) {
      if (row.isTotal) {
        return 'total-row'
      }
      return ''
    },

    handleInspectionToggleEdit() {
      if (!this.inspectionEditStatus) {
        this.inspectionTableDataBackup = JSON.parse(JSON.stringify(this.inspectionTableDataRaw))
        this.inspectionEditStatus = true
      } else {
        this.$confirm('是否取消编辑并放弃修改?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '继续编辑',
          type: 'warning'
        }).then(() => {
          this.inspectionTableDataRaw = JSON.parse(JSON.stringify(this.inspectionTableDataBackup))
          this.inspectionEditStatus = false
          this.inspectionTableDataBackup = []
        }).catch(() => {})
      }
    },

    handleInspectionRefresh() {
      this.inspectionTableLoading = true
      setTimeout(() => {
        this.inspectionTableDataRaw = this.getInspectionMockData()
        this.inspectionTableLoading = false
      }, 500)
    },

    handleInspectionSave() {
      this.$confirm('确认保存当前修改?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        setTimeout(() => {
          this.$message.success('保存成功')
          this.inspectionEditStatus = false
          this.inspectionTableDataBackup = []
          console.log('保存的检验统计数据:', this.inspectionTableDataRaw)
        }, 500)
      }).catch(() => {})
    },

    handleInspectionRefresh() {
      this.inspectionTableLoading = true
      setTimeout(() => {
        this.inspectionTableDataRaw = this.getInspectionMockData()
        this.inspectionTableLoading = false
        this.$message.success('刷新成功')
      }, 500)
    },

    /**
     * 处理分报表模板切换
     */
    handleInspectionTemplateChange(value) {
      console.log('切换分报表模板:', value)
      // 根据模板加载对应数据
      this.inspectionTableLoading = true
      setTimeout(() => {
        this.inspectionTableDataRaw = this.getInspectionMockData()
        this.inspectionTableLoading = false
        this.$message.success('模板切换成功')
      }, 500)
    },

    /**
     * 处理分报表查询
     */
    handleInspectionSearch() {
      console.log('分报表查询参数:', {
        template: this.selectedInspectionTemplate,
        date: this.inspectionSearchForm.date
      })
      this.inspectionSearchLoad = true
      this.inspectionTableLoading = true
      setTimeout(() => {
        this.inspectionTableDataRaw = this.getInspectionMockData()
        this.inspectionSearchLoad = false
        this.inspectionTableLoading = false
        this.$message.success('查询成功')
      }, 500)
    },

    /**
     * 处理分报表重置
     */
    handleInspectionReset() {
      this.inspectionSearchForm.date = ''
      this.selectedInspectionTemplate = this.INSPECTION_TEMPLATE_OPTIONS[0].value
      this.$message.success('重置成功')
      // 重新加载数据
      this.handleInspectionSearch()
    },

    /**
     * 处理月报表模板切换
     */
    handleMonthlyTemplateChange(value) {
      console.log('切换月报表模板:', value)
      this.monthlyTableLoading = true
      setTimeout(() => {
        this.monthlyTableDataRaw = this.getMonthlyMockData()
        this.monthlyTableLoading = false
        this.$message.success('模板切换成功')
      }, 500)
    },

    /**
     * 处理月报表查询
     */
    handleMonthlySearch() {
      console.log('月报表查询参数:', {
        template: this.selectedMonthlyTemplate,
        date: this.monthlySearchForm.date
      })
      this.monthlySearchLoad = true
      this.monthlyTableLoading = true
      setTimeout(() => {
        this.monthlyTableDataRaw = this.getMonthlyMockData()
        this.monthlySearchLoad = false
        this.monthlyTableLoading = false
        this.$message.success('查询成功')
      }, 500)
    },

    /**
     * 处理月报表重置
     */
    handleMonthlyReset() {
      this.monthlySearchForm.date = ''
      this.selectedMonthlyTemplate = this.MONTHLY_TEMPLATE_OPTIONS[0].value
      this.$message.success('重置成功')
      this.handleMonthlySearch()
    },

    /**
     * 处理月报表刷新
     */
    handleMonthlyRefresh() {
      this.monthlyTableLoading = true
      setTimeout(() => {
        this.monthlyTableDataRaw = this.getMonthlyMockData()
        this.monthlyTableLoading = false
        this.$message.success('刷新成功')
      }, 500)
    },

    handleInspectionAddRow({ row, position }) {
      const newRow = this.createInspectionNewRow(row, position)
      const index = this.inspectionTableDataRaw.findIndex(item => item.id === row.id)

      if (index === -1) {
        this.$message.error('未找到选中的行')
        return
      }

      if (position === 'before') {
        this.inspectionTableDataRaw.splice(index, 0, newRow)
      } else {
        this.inspectionTableDataRaw.splice(index + 1, 0, newRow)
      }

      this.$message.success('添加成功')
    },

    createInspectionNewRow(baseRow, position) {
      return {
        id: `inspection_${Date.now()}`,
        system: baseRow.system,
        productName: baseRow.productName,
        inspectedCount: 0,
        qualifiedCount: 0,
        wasteCount: 0,
        pendingCount: 0,
        waste_drop: 0,
        waste_verticalCrack: 0,
        waste_oxidation: 0,
        waste_tempCrack: 0,
        waste_damage: 0,
        pending_drop: 0,
        pending_verticalCrack: 0,
        pending_tempCrack: 0,
        pending_damage: 0,
        pending_bag: 0,
        pending_oxidation: 0
      }
    },

    handleInspectionDeleteRow({ rows }) {
      const idsToDelete = rows.map(row => row.id)

      this.inspectionTableDataRaw = this.inspectionTableDataRaw.filter(
        row => !idsToDelete.includes(row.id)
      )

      const count = rows.length
      this.$message.success(`成功删除 ${count} 行数据`)
    }
  }
}
</script>

<style lang="scss" scoped>
.material {
  padding: 5px;
  background-color: #fafafa;
  transition: all 0.3s ease;

  &.fullscreen {
    padding: 0;
    margin: 0;
    height: 100vh;
    background-color: #fff;
    overflow: hidden;
  }
}

.list-box {
  padding: 8px;
  border: none;
  overflow: hidden;

  ::v-deep .el-card__body {
    overflow: hidden !important;
  }
}

.select-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 8px;

  ::v-deep .el-form {
    margin-bottom: 0;
  }

  ::v-deep .el-form-item {
    margin-bottom: 0;
    margin-right: 0;
  }

  ::v-deep .el-select--mini {
    width: 130px;
  }

  ::v-deep .el-date-editor--date {
    width: 160px;
  }
}

.table-title {
  text-align: center;
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 8px;
  padding: 4px 0;
  border-bottom: 1px solid #e4e7ed;
}

.tab-placeholder {
  text-align: center;
  padding: 80px 0;
  color: #999;
}

::v-deep .el-card__body {
  overflow: hidden !important;
  padding: 8px !important;
}

::v-deep .fullscreen .el-tabs__header {
  display: none !important;
}

::v-deep .fullscreen .select-wrapper {
  display: none !important;
}

::v-deep .fullscreen .table-title {
  display: none !important;
}

// 合计行和小计行样式
::v-deep .total-row {
  background-color: #f0f5ff !important;
  font-weight: 600 !important;

  td {
    background-color: #f0f5ff !important;
    color: #303133 !important;
    border-bottom: 2px solid #409EFF !important;
  }

  .cell {
    font-weight: 600 !important;
  }
}
</style>
